package com.simple.gateway.core.network;

import com.simple.gateway.core.network.handlers.AuthorizationHandler;
import com.simple.gateway.core.network.handlers.GatewayServerHandler;
import com.simple.gateway.core.network.handlers.ProtocolDataHandler;
import com.simple.gateway.core.session.Configuration;
import com.simple.gateway.core.session.defaults.DefaultGatewaySessionFactory;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;

/**
 * 项目: simple-gateway-core
 * <p>
 * 功能描述: session通道初始化
 *
 * @author: WuChengXing
 * @create: 2023-08-02 11:21
 **/
public class GatewayChannelInitializer extends ChannelInitializer<SocketChannel> {

    private final Configuration configuration;
    private final DefaultGatewaySessionFactory gatewaySessionFactory;

    public GatewayChannelInitializer(Configuration configuration, DefaultGatewaySessionFactory gatewaySessionFactory) {
        this.configuration = configuration;
        this.gatewaySessionFactory = gatewaySessionFactory;
    }

    @Override
    protected void initChannel(SocketChannel channel) throws Exception {
        ChannelPipeline line = channel.pipeline();
        line.addLast(new HttpRequestDecoder());
        line.addLast(new HttpResponseEncoder());
        // HttpObjectAggregator 用于处理除了GET 请求外的POST请求时候的对象信息，否则只有上面的信息，是拿不到POST请求的
        line.addLast(new HttpObjectAggregator(1024 * 1024));
        line.addLast(new GatewayServerHandler(configuration));
        line.addLast(new AuthorizationHandler());
        line.addLast(new ProtocolDataHandler(gatewaySessionFactory));
    }
}
